import json

from flask_restful import Resource, reqparse, request
from comment.models.index import *
from comment.utils.data2dict import data2dict, datalist2dict
from comment.utils.shopping_redis import redis_client

# 商品分类的资源类
class Shopping_Category(Resource):

    def get(self):
        data_cache = redis_client.get("index_category")
        if data_cache:  # 如果redis中有数据，则直接返回redis中的数据
            return json.loads(data_cache)
        else:           # 如果Redis中没有数据，则从mysql中查询数据，返回给用户，同时将数据写入Redis
            rq = reqparse.RequestParser()
            rq.add_argument("parent_id", required=True, type=int)
            req = rq.parse_args()
            data = self.getDate(parent_id)
            if data:
                for item in data:
                    item.update({"list": ''})
                    date_second = self.getDate(item["id"])
                    item['list'] = date_second
                    for item1 in date_second:
                        item1.update({"list": ''})
                        date_three = self.getDate(item1["id"])
                        item1['list'] = date_three
                redis_client.setex("index_category", 60*60*24, json.dumps(data))    # 将数据写入到Redis 保存24小时 dumps将字典转化为字符串
                return data
            else:
                return {'message': "None"}

    @staticmethod
    def getDate(parent_id):
        res = Category.query.with_entities(Category.id, Category.parent_id, Category.name).filter(Category.parent_id==parent_id).order_by(Category.sort.asc()).limit(10).all()
        if res:
            return datalist2dict(res)
        else:
            return None

# data2dict 测试类
class Dict_test(Resource):

    def get(self):
        res = Category.query.filter(Category.parent_id==0).all()    # 取多条数据 所有字段
        res = Category.query.with_entities(Category.id, Category.name).filter(Category.parent_id==0).all()  # 只取了两个字段
        if res:
            return datalist2dict(res)
        else:
            return None


# 首页新品推荐的模型类
class Shopping_HomeNewProduct(Resource):
    def get(self):
        res = HomeNewProduct.query.join(Product, HomeNewProduct.product_id==Product.id).with_entities(
            Product.id, Product.default_pic, Product.price, Product.product_name, Product.rel_category3_id).order_by(HomeNewProduct.sort.asc()).limit(10).all()

        if res:
            return datalist2dict(res)
        else:
            return {'message': None}

# 首页人气热搜的资源类    从redis中查询
class Shopping_HomeRecommendProduct(Resource):
    def get(self):
        data_cache = redis_client.get("index_HomeRecommendProduct")
        if data_cache:
         return json.loads(data_cache)
        else:
            res = HomeRecommendProduct.query.join(Product, HomeRecommendProduct.product_id==Product.id).with_entities(
                 Product.id, Product.default_pic, Product.product_name, Product.rel_category3_id, Product.price).limit(10).all()

            if res:
                data = datalist2dict(res)
                 # 将数据写入到redis
                redis_client.setex('index_HomeRecommendProduct', 60*60*24, json.dumps(data))
                return data
            else:
                return {"message": None}

# 首页专题广场资源类
class Shopping_Recommend_Subject(Resource):
    def get(self):
        data_cache = redis_client.get("index_RecommendSubject")

        # 从redis中读取数据
        if data_cache:
            return json.loads(data_cache)
        else:
            res = CmsSubject.query.filter(CmsSubject.show_status==1).all()
            if res:
                data = datalist2dict(res)
                for i in range(len(data)):
                    res_product = (CmsSubjectProductRelation.query.join(Product, CmsSubjectProductRelation.product_id==Product.id).filter(CmsSubjectProductRelation.subject_id==data[i]["id"])
                               .with_entities(Product.id, Product.default_pic, Product.price, Product.rel_category3_id).limit(10).all())
                    if res_product:
                        data[i]["productList"] = datalist2dict(res_product)
                    else:
                        data[i]["productList"] = ""

                redis_client.setex('index_RecommendSubject', 60*60*24, json.dumps(data))
                return data
            else:
                return {'message':None}
